package com.hzcx.app.simplechat.api;


import com.hzcx.app.simplechat.MyApplication;
import com.hzcx.app.simplechat.event.TokenErrorEvent;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.net.NetWorkUtils;
import com.hzcx.app.simplechat.util.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;


/**
 * 网络请求返回统一处理
 *
 * @param <T>
 */
public abstract class BaseObserver<T> implements HttpResponce, Observer<BaseResponse<T>> {

    private static final String TAG = "BaseObserver";

    @Override
    public void onSubscribe(Disposable d) {
        if (!NetWorkUtils.isConnted(MyApplication.getContext())) {
            onFailure(null, "网络连接失败，请检查您的网络设置");
            d.dispose();
        }
    }

    @Override
    public void onNext(BaseResponse<T> tBaseResponse) {
        if (tBaseResponse.getCode() == 401) {
            LogUtils.e(TAG, "token过期");
            EventBus.getDefault().post(new TokenErrorEvent());
            return;
        }
        if (tBaseResponse.getCode() != 100) {
            onFailure(null, tBaseResponse.getMsg());
        } else {
            onSuccess(tBaseResponse.getData());
        }
    }

    @Override
    public void onComplete() {
    }

    protected abstract void onSuccess(T data);

    @Override
    public void onError(Throwable e) {
        LogUtils.e(TAG, "onError:" + e.getMessage());
        if (e instanceof HttpException) {
            try {
                HttpException httpException = (HttpException) e;
                if (httpException.code() == 401) {
                    LogUtils.e(TAG, "token过期");
                    EventBus.getDefault().post(new TokenErrorEvent());
                } else {
                    onFailure(e, RxExceptionUtil.exceptionHandler(e));
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                onFailure(e, RxExceptionUtil.exceptionHandler(e));
            }

        } else {
            onFailure(e, RxExceptionUtil.exceptionHandler(e));
        }
    }

    @Override
    public void onFailure(Throwable e, String errorMsg) {
        if (EmptyUtils.isNotEmpty(errorMsg)) {
            ToastUtils.show(errorMsg);
        }
    }
}
